package com.wuliu.driver.util;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
@Component
public class FileConvertUtil {
    public static MultipartFile convert(File file) throws Exception {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        FileItem item = factory.createItem("file", "image/png", false, file.getName());

        // 将文件内容复制到FileItem中
        try (FileInputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) >= 0) {
                os.write(buffer, 0, len);
            }
        }

        return new CommonsMultipartFile(item);
    }
}
